package com.handu.luna.core.domain.goods;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.Entity;
import javax.persistence.Transient;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import org.apache.commons.lang.StringUtils;

import com.handu.luna.core.domain.BasePersistentDomain;



@Entity
public class Category extends BasePersistentDomain<CategoryRepository>{

	private long parentId;
	private String attributeIds; //属性id
	private String parentCollection;  //在孩子的分类上存储所有的  上级分类（即孙子的分类上包括 爷爷和父亲）
 
	@NotNull(message="分类长度不能为空")
 	@Size(min=1,max=100, message="分类名称长度不能为空或超过100字。")
	private String name;
	
	@Min(0) 
	@Max(value=254,message="最大不能超过255")
	private int displayOrder =100 ;
	private boolean displayed;   //是否显示
	private boolean navigation;  //导航
  
	private String keywords;
	private String title;
	private String description;
  
	@Transient
	private long goodsNum;
	
	@Transient
    protected List<Long> attributeIdList;
	
    /**
     * 数据库到视图的字段转化
     * @param bonusPromotion
     */
    public void fromDateBaseToView(Category category) {
    	category.setAttributeIdList(getAttributeIdListFromString(category.getAttributeIds()));
    }

    /**
     * 视图到数据库的字段转化
     * @param bonusPromotion
     */
    public void fromViewToDateBase(Category category) {
    	category.setAttributeIds(getStringFromAttributeIdList(category.getAttributeIdList()));
    }

    
    /**
     * 将数据库存储的品牌ID字符串序列转换为IdList
     * @param attributeIds
     * @return
     */
    public List<Long> getAttributeIdListFromString(String attributeIds) {
        List<Long> attributeIdList = new ArrayList<>();
        if(StringUtils.isBlank(attributeIds)) {
            return attributeIdList;
        }
        String[] strArr = attributeIds.split(",");
        for(String str : strArr) {
            try {
                Long attributeId = Long.parseLong(str);
                attributeIdList.add(attributeId);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
        return attributeIdList;
    }public long getGoodsNum() {
		return goodsNum;
	}

    /**
     * 将attributeIdList转换为数据库存储的字符序列，以“，”分隔
     * @param attributeIdList
     * @return
     */
    public String getStringFromAttributeIdList(List<Long> attributeIdList) {
        if(null == attributeIdList || attributeIdList.size() == 0) {
            return "";
        }

        StringBuilder sb = new StringBuilder();
        for(int i=0; i<attributeIdList.size(); i++) {

            sb.append(attributeIdList.get(i).toString());
            if(i==attributeIdList.size()-1) {
                break;
            }
            sb.append(",");
        }
        return sb.toString();
    }
    
	public void setGoodsNum(long goodsNum) {
		this.goodsNum = goodsNum;
	}

	public Category(long id,String name,String attributeIds, List<Long> attributeIdList,long parentId, int displayOrder,
			boolean displayed,boolean navigation,int cat_recommend) {
		super();
		this.id=id;
		this.name = name;
		this.parentId = parentId;
		this.displayOrder = displayOrder;
		this.displayed = displayed;
		this.navigation =navigation; 
		this.attributeIdList = attributeIdList;
		this.attributeIds = attributeIds;
		this.keywords="";
		this.description="";
		this.title="";
	 
	}
	public Category(long id,String parentCollection,String name,long parentId, int displayOrder,
			boolean displayed,boolean navigation,int cat_recommend) {
		super();
		this.id=id;
		this.parentCollection = parentCollection;
		this.name = name;
		this.parentId = parentId;
		this.displayOrder = displayOrder;
		this.displayed = displayed;
		this.navigation =navigation; 
		this.keywords="";
		this.description="";
		this.title="";
	 
	}
	
	public void initSubCategories(List<Category> allCategories){
		if(this.subCategories==null)this.subCategories = new ArrayList<Category>();
		for(Category each : allCategories){
			if(this.getId() == each.getParentId()){
				this.subCategories.add(each);
			}
		}
		for(Category eachSub : subCategories){
			eachSub.initSubCategories(allCategories);
		}			
	}
	public void addSelfToList(List<Category> categorieTableList){
		categorieTableList.add(this);
		if(this.subCategories!=null){
			for(Category eachSub : subCategories){
				eachSub.addSelfToList(categorieTableList);
			}	
		}
	}	 

	@Transient
	private List<Category> subCategories;
    public Category(){
    	
    }
	public Category(long id,String name ) {
		super();
		this.id =id;
		this.name = name;
 	}
	public long getParentId() {
		return parentId;
	}
	public void setParentId(long parentId) {
		this.parentId = parentId;
	}
	
	
	public String getParentCollection() {
		return parentCollection;
	}

	public void setParentCollection(String parentCollection) {
		this.parentCollection = parentCollection;
	}

	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getDisplayOrder() {
		return displayOrder;
	}
	public void setDisplayOrder(int displayOrder) {
		this.displayOrder = displayOrder;
	}
	public boolean isDisplayed() {
		return displayed;
	}
	public void setDisplayed(boolean displayed) {
		this.displayed = displayed;
	}
	public boolean isNavigation() {
		return navigation;
	}
	public void setNavigation(boolean navigation) {
		this.navigation = navigation;
	}
	public String getKeywords() {
		return keywords;
	}
	public void setKeywords(String keywords) {
		this.keywords = keywords;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getDescription() {
		return description;
	}
	public void setDescription(String description) {
		this.description = description;
	}
 
	public List<Category> getSubCategories() {
		return subCategories;
	}
	public void setSubCategories(List<Category> subCategories) {
		this.subCategories = subCategories;
	}

	public String getAttributeIds() {
		return attributeIds;
	}

	public void setAttributeIds(String attributeIds) {
		this.attributeIds = attributeIds;
	}

	public List<Long> getAttributeIdList() {
		return attributeIdList;
	}

	public void setAttributeIdList(List<Long> attributeIdList) {
		this.attributeIdList = attributeIdList;
	}

	/**
	 * 多表查询的   初始化信息
	 */
	public void init(long id,boolean isContainUndisplayed){
		if(id == 0 ){
			id = this.id;
		}
		//goodsNum += context.getGoodsRepository().count("categoryId",id);getNumByCatId
		if(isContainUndisplayed){
			goodsNum += context.getGoodsRepository().getNumByCatId4Portal(id);
		}else{
			goodsNum += context.getGoodsRepository().getNumByCatId(id);
		}
		
		List<Category> childs = context.getCategoryRepository().getAllByCatId(id);  //判断该分类下有没有子分类
		if(!childs.isEmpty()){
			for(Category List : childs){
				init(List.getId(),isContainUndisplayed);
			}
		}
		
	}
	

    public Category save(Category category) {

        fromViewToDateBase(category);
        return context.getCategoryRepository().save(category);

    }

    public Category findOne(Long id) {

    	Category category = context.getCategoryRepository().findOne(id);
        fromDateBaseToView(category);
        return category;
    }

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result
				+ ((attributeIdList == null) ? 0 : attributeIdList.hashCode());
		result = prime * result
				+ ((attributeIds == null) ? 0 : attributeIds.hashCode());
		result = prime * result
				+ ((description == null) ? 0 : description.hashCode());
		result = prime * result + displayOrder;
		result = prime * result + (displayed ? 1231 : 1237);
		result = prime * result + (int) (goodsNum ^ (goodsNum >>> 32));
		result = prime * result
				+ ((keywords == null) ? 0 : keywords.hashCode());
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		result = prime * result + (navigation ? 1231 : 1237);
		result = prime
				* result
				+ ((parentCollection == null) ? 0 : parentCollection.hashCode());
		result = prime * result + (int) (parentId ^ (parentId >>> 32));
		result = prime * result
				+ ((subCategories == null) ? 0 : subCategories.hashCode());
		result = prime * result + ((title == null) ? 0 : title.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (!super.equals(obj))
			return false;
		if (getClass() != obj.getClass())
			return false;
		Category other = (Category) obj;
		if (this.id == other.id) {
			return true;
		}
		return false;
	}
	 
}
